package com.example.demo.controller;


import com.example.demo.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class UserContrller {
    private String newname;
    @Autowired
    private Random random;
    @RequestMapping("/upload")
    public String uppic(@RequestParam("pic") List<MultipartFile> upfile){
        if(upfile.size()>0&&!upfile.isEmpty()) {
            for(MultipartFile file:upfile) {
                String filename=file.getOriginalFilename();
                String dirpath="D:\\picture\\images\\java\\";
                File filepath=new File(dirpath);
                if(!filepath.exists()) {
                    filepath.mkdirs();
                }
                String code=random.randomCode();
                newname=code+filename;
                try {
                    file.transferTo(new File(dirpath+newname));
                } catch (Exception e) {
                    // TODO: handle exception
                    return "上传失败!";
                }
            }
            return "http://localhost:9090/images/java/"+newname;
        }else {
            return "上传失败!";
        }

    }
    /*
    * 多文件上传
    * */
    @RequestMapping("/upload2")
    @ResponseBody
    public List<String> uppics(@RequestParam("pics") MultipartFile[] files) {
        //判断是否有图片上传,有则上传图片，无则直接存储数据
        List<String> list=new ArrayList<>();
        if (files.length > 0) {
            System.out.println(files.length);
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();

                String newFileName = random.randomCode()+fileName;
                String dirpath = "D:\\picture\\images\\java\\";
                File uploadPathFile = new File(dirpath + newFileName);
                if (!uploadPathFile.exists()) {
                    uploadPathFile.mkdirs();
                }
                try {
                    // 构建真实的文件路径
                    file.transferTo(uploadPathFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                list.add("http://localhost:9090/images/java/"+newname);
            }
        }
        return list;
    }


}
